#include "18b20.h"
#include "intrins.h"
#include "delay.h"

void ds18b20_write_bit(unsigned char b) 
{
	if(b&0x01) {
		DS18B20 = 0;
		_nop_();_nop_();
		DS18B20 = 1;//MCU释放总线;
		delay(6);
	} else {
		DS18B20 = 0;
		delay(6);
		DS18B20 = 1;
		_nop_();_nop_();
	}
}

void ds18b20_write_byte(unsigned char byte)  
{
	unsigned char i = 0;
	for( ;i<8; ++i) 
	{
		ds18b20_write_bit( byte & 0x01 );
		byte >>= 1;
	}
}
	
unsigned char ds18b20_read_bit() 
{
	unsigned char ret = 0;
	DS18B20 = 0;
	_nop_();_nop_();
	DS18B20 = 1;//MCU释放总线;
	_nop_();_nop_();
	if(DS18B20) 
	{
		ret = 0x80;
	}
	delay(6);
	return ret;
}

unsigned char ds18b20_read_byte() 
{
	unsigned char i = 0;
	unsigned char dat = 0;
	for( ;i<8; ++i) 
	{
		dat >>= 1;
		dat |= ds18b20_read_bit();
	}
	return dat;
}

void ds18b20_reset() 
{
	DS18B20 = 0;
	delay(60);// 600us
	DS18B20 = 1;//MCU释放总线;
	delay(2);
	while(DS18B20);//等待18B20回应
	while(!DS18B20);//等待18B20释放总线
}

unsigned char DS1820ROM[8];

void ds18b20_read_rom() 
{
	unsigned char i = 0;
	ds18b20_reset();
	ds18b20_write_byte(0x33);
	for( ;i<8;++i) 
	{
		DS1820ROM[i] = ds18b20_read_byte();
	}
}

void ds18b20_read_temputer(float* ptr) 
{
	unsigned char temp_L = 0;
	unsigned int temp = 0;
	ds18b20_reset();
	ds18b20_write_byte(0xCC);//跳过ROM操作
	ds18b20_write_byte(0x44);//开始转换温度
	delay(5000);
	ds18b20_reset();
	ds18b20_write_byte(0xCC);
	ds18b20_write_byte(0xBE);//读温度
	
	temp_L = ds18b20_read_byte();
	temp = ds18b20_read_byte();
	temp = (temp << 8) | temp_L;
	if(temp & 0x8000) 
	{
		temp = (~temp + 1);
	}
	*ptr = temp * 0.0625f;
}